import addressList from '@/components/Address/list'
import { freight } from '@/api/shipping'
import { create, addShoppingCart } from '@/api/goodIndent'
import { detail as getUserDetail } from '@/api/user'

export default {
  components: {
    addressList
  },
  layout: 'cart',
  middleware: 'auth',
  head() {
    return {
      title: this.$t('indent.title') + '-' + process.env.APP_NAME
    }
  },
  data() {
    const validateRemark = (rule, value, callback) => {
      const flag = new RegExp("[`~!@#$^&*()=|{}':'\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘：”“'。？ ]")
      if (flag.test(value)) {
        return callback(new Error(this.$t('header.top.validate_remark')))
      } else {
        callback()
      }
    }
    return {
      loading: true,
      buttonLoading: false,
      total: 0,
      integral: 0,
      bl: '',
      type: 0,
      totalPoints: "",//总积分
      usePoints: "",//使用积分
      ruleForm: {
        indentCommodity: [],
        address: '',
        remark: '',
        carriage: 0
      },
      rules: {
        remark: [{ validator: validateRemark, trigger: 'blur' }]
      },
      isAddress: true,
      visible: false
    }
  },
  async asyncData(ctx) {
    try {
    } catch (err) {
      ctx.$errorHandler(err)
    }
  },
  created() {
    getUserDetail().then((res) => {
      this.totalPoints = res.integral || 0
      this.bl = res.bl * 1 || 1
      console.log("🚀 ~  res: ", this.bl)
    })
  },
  mounted() {
    $nuxt.$store.commit('setCartTitle', this.$t('indent.title'))
    this.getList()
  },
  methods: {
    handleChoose(type) {
      this.type = type
      // 选择积分校验
      console.log(this.integral)
      if (type == 1) {
        if (this.integral > this.totalPoints * this.bl) {
          this.$message.warning('당신의 현재 사용 포인트는 이 주문서의 최대 포인트 한도보다 큽니다')
          return false
        }
        if (this.integral > this.total) {
          this.$message.warning('당신의 현재 사용 포인트는 이 주문 금액보다 큽니다')
          return false
        }
        this.usePoints = this.integral
        this.visible = false
      } else {
        this.usePoints = 0
        this.visible = false
      }
    },
    async getList() {
      let specification = null
      this.ruleForm.indentCommodity = Object.values(this.store.get(process.env.CACHE_PR + 'OrderList'))
      console.log('🚀 ~  this.ruleFor: ', this.store, this.ruleForm)
      let data = []
      this.ruleForm.indentCommodity.forEach(item => {
        // price 有bug
        this.total += item.price * item.number
        console.log("🚀 ~  this.total: ", this.total)
        if (item.good_sku) {
          specification = null
          item.good_sku.product_sku.forEach(item2 => {
            if (specification) {
              specification += item2.value + ';'
            } else {
              specification = item2.value + ';'
            }
          })
          item.specification = specification.substr(0, specification.length - 1)
          data.push({
            ids: item.good_id,
            price: item.good_sku.price,
            skuIds: item.good_sku_id
          })
        }
      })
      // 是否需要地址
      // this.isAddress = this.ruleForm.indentCommodity.some(function(item) {
      //   return item.good.type === $nuxt.$t('good.type.common')
      // })
    },
    // 选择的地址
    selectedAddress(res) {
      // console.log('🚀 ~  res: ', res)
      this.buttonLoading = true
      this.ruleForm.address = res
      const indentCommodity = this.ruleForm.indentCommodity.map(item => {
        return { number: item.number, freight_id: item.good.freight_id }
      })
      freight(res.id, indentCommodity).then(response => {
        this.ruleForm.carriage = response.carriage
        this.buttonLoading = false
      })
    },
    // 提交订单
    submit() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          if (!this.ruleForm.address) {
            this.$message({
              message: '주소는 비워둘 수 없습니다.',
              type: 'error'
            })
            return false
          }
          this.buttonLoading = true
          // 这里处理下  使用了多少积分
          const indentCommodity = this.ruleForm.indentCommodity.map(item => {
            return {
              number: item.number,
              name: item.name,
              good_id: item.good_id,
              img: item.img,
              good_sku_id: item.good_sku_id ? item.good_sku_id : 0,
              freight_id: item.good.freight_id,
              price: item.price,
              integral: item.integral
            }
          })
          console.log((((this.ruleForm.carriage + this.total - (this.usePoints * 1)) * 100) / 100))
          if ((((this.ruleForm.carriage + this.total - (this.usePoints * 1)) * 100) / 100) < 200) {
            this.$message({
              message: '결제 금액 최소 200원이상 입니다',
              type: 'error'
            })
            this.buttonLoading = false
            return false
          }
          // return false
          create({
            indentCommodity,
            remark: this.ruleForm.remark,
            carriage: this.ruleForm.carriage,
            shipping_id: this.ruleForm.address.id,
            integral_money: this.integral || 0, //  积分
            use_integral: this.integral || 0
          })
            .then(response => {
              this.buttonLoading = false
              this.store.remove(process.env.CACHE_PR + 'CartList')
              this.store.remove(process.env.CACHE_PR + 'OrderList')
              addShoppingCart([])
              $nuxt.$router.replace({ path: '/money/pay', query: { id: response } })
            })
            .catch(() => {
              this.buttonLoading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    go() {
      $nuxt.$router.go(-1)
    }
  }
}
